<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="80px" :rules="formRules">
                <el-form-item label="父级分类" prop="pid">
                    <el-tree-select
                        class="flex-1"
                        v-model="formData.pid"
                        :data="menuOptions"
                        clearable
                        node-key="id"
                        :props="{
                            label: 'name'
                        }"
                        :default-expand-all="true"
                        placeholder="请选择父级分类"
                        check-strictly
                    />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入分类名称" clearable />
                </el-form-item>
                <el-form-item label="图标" prop="icon">
                    <div>
                        <div>
                            <material-picker v-model="formData.icon" :limit="1" />
                        </div>
                        <div class="form-tips">建议尺寸：20*20px，支持jpg，jpeg，png格式</div>
                    </div>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <div>
                        <el-input-number v-model="formData.sort" :max="9999" />
                        <div class="form-tips">数值越大越排前</div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { MenuEnum } from '@/enums/appEnums'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import { arrayToTree, treeToArray } from '@/utils/util'

import {
    listTree as menuLists,
    edit as menuEdit,
    detail1 as menuDetail,
    add as menuAdd
} from '@/servers/goods/api/supplyChainshangpinfenlei'

let id: any
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑分类' : '新增分类'
})

const formData = reactive({
    //父级id
    pid: 0,
    name: '',
    icon: undefined,
    sort: 0
})

const formRules = {
    pid: [
        {
            required: true,
            message: '请选择父级分类',
            trigger: ['blur', 'change']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
        }
    ]
}
const menuOptions = ref<any[]>([])

const getMenu = async () => {
    const data: any = await menuLists({})
    const menu: any = { id: 0, name: '顶级', children: [] }
    menu.children = arrayToTree(
        treeToArray(data).filter((item) => item.menuType != MenuEnum.BUTTON)
    )
    menuOptions.value.push(menu)
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit'
        ? await menuEdit(
              {
                  id
              },
              formData
          )
        : await menuAdd(formData)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    id = row.id
    const data = await menuDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    id = undefined
    emit('close')
}

getMenu()

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
